package org.xiangfei.route;

import java.util.Properties;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.xiangfei.route.handler.ProxyServerInitializer;

/**
 * 
 * @author xiangfei
 *
 */
public class XFProxyServer {
    private static final InternalLogger logger
    =InternalLoggerFactory.getInstance(XFProxyServer.class);  

//    private static final Logger logger = LoggerFactory.getLogger(ProxyServer.class);
    private static int local_port = 0;
    private static String remote_host = "";
    private static int remote_port = 0;

    private boolean loadConfig(){  
        Properties properties = new Properties();  
        try {  
            properties.load(getClass().getResourceAsStream("/application.properties")); 
            local_port = Integer.parseInt(properties.getProperty("local_port"));
            remote_port = Integer.parseInt(properties.getProperty("remote_port"));
            remote_host = properties.getProperty("remote_host");
        } catch (Exception e) {  
            logger.error("load config error" , e);
            return false;
        }  
        return true;
    }  
      
   
    private void run()  {
        System.out.println("starting route server " + local_port + remote_port + remote_host);

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ProxyServerInitializer(remote_host, remote_port))
             .childOption(ChannelOption.AUTO_READ, false)
             .bind(local_port).sync().channel().closeFuture().sync();
            logger.info("started route server port = {}, remote_port={}, remote_host={}", local_port, remote_port, remote_host);

        } catch(Exception e) {
            logger.error("route server error" , e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        XFProxyServer server = new XFProxyServer();
        if (server.loadConfig()) {
            server.run();
        }
    }
}
